import './SetAdminOptions.scss'
import { v4 } from 'uuid'
import { useState } from 'react'
import { useEventEmitter, useMount } from 'ahooks'
import { Button, Popover, Tree, Popconfirm, App } from "antd"


import { removeTreeByKey } from '../../Utils'
import { AdminRouter } from '../../Config/default'
import { FormTempMapping } from '../../Utils/FormTemp'
import { FlowThemeFormMapping } from '../../Config/FlowConfig'
import { SetOptionsField, SetSearchField, SetSortField } from '../../Utils/DndKit'


const SetAdminOptions = ({ data, Off }) => {
    const { notification, message } = App.useApp()
    const { type, FORMEVENT, init, options } = data
    const [FieldArr, setFieldArr] = useState(init)

    FORMEVENT.useSubscription(val => {
        const { type, data } = val
        if (type === 'onClearBox') Off()
        if (type === 'onUpdateField') setFieldArr(data)
    })



    if (type === 'AddOptions') {
        const FormMappign = { top: 'FlowMenuTopClick', row: 'FlowMenuRowClick' }
        return (
            <div className="AddOptions">
                <FormTempMapping
                    formItem={FlowThemeFormMapping[FormMappign[data.data]]}
                    FORMEVENT={FORMEVENT}
                    Initial={AdminRouter[FormMappign[data.data]]}
                />
            </div>
        )
    }

    if (type === 'setField') {
        const onSaveField = () => {
            const newArr = FieldArr.map(({ id, visible, dataField, caption, rules }) =>
                ({ id, visible, dataField, caption, rules }))
            FORMEVENT.emit({ type: 'onSaveField', data: newArr })
            Off()
        }
        return (
            <div className='SetField'>
                <SetOptionsField data={init.filter(v => v.status !== 0)} FieldEvent={FORMEVENT} />
                <div>
                    <Button type='primary' onClick={onSaveField}>保存字段</Button>
                </div>
            </div>
        )
    }

    if (type === 'setSearch') {
        const onSaveField = () => {
            FORMEVENT.emit({ type: 'onSaveField', data: FieldArr })
            Off()
        }
        const [open, setOpen] = useState(false)

        const SearchEvent = useEventEmitter()
        SearchEvent.useSubscription(val => {
            const { type, data } = val
            if (type === 'onFormBack') {
                FORMEVENT.emit({ type: 'onAddField', data })
                setOpen(false)
            }
        })

        return (
            <div className='SetField'>
                <SetSearchField data={init} FieldEvent={FORMEVENT} />
                <div>
                    <Popover
                        content={<FormTempMapping formItem={FlowThemeFormMapping['SearchFiledForm']} FORMEVENT={SearchEvent} />}
                        destroyOnHidden
                        title="新增查询字段"
                        trigger="click"
                        open={open}
                        onOpenChange={setOpen}
                    >
                        <Button type='primary'>新增字段</Button>
                    </Popover>
                    <Button type='primary' onClick={onSaveField}>保存字段</Button>
                </div>
            </div>
        )
    }

    if (type === 'setSort') {
        const onSaveField = () => {
            FORMEVENT.emit({ type: 'onSaveField', data: FieldArr })
            Off()
        }
        const [open, setOpen] = useState(false)

        const SearchEvent = useEventEmitter()
        SearchEvent.useSubscription(val => {
            const { type, data } = val
            if (type === 'onFormBack') {
                FORMEVENT.emit({ type: 'onAddField', data })
                setOpen(false)
            }
        })
        return (
            <div className='SetField'>
                <SetSortField data={init} FieldEvent={FORMEVENT} />
                <div>
                    <Popover
                        content={<FormTempMapping formItem={FlowThemeFormMapping['SortFiledForm']} FORMEVENT={SearchEvent} />}
                        destroyOnHidden
                        title="新增查询字段"
                        trigger="click"
                        open={open}
                        onOpenChange={setOpen}
                    >
                        <Button type='primary'>新增字段</Button>
                    </Popover>
                    <Button type='primary' onClick={onSaveField}>保存字段</Button>
                </div>
            </div>
        )
    }
    if (type === 'setOptions') {
        const CLASSMAPPING = {
            A00: 'A00Options',
            A01: 'A01Options',
            A02: 'A02Options',
            A03: 'A03Options',
            A04: 'A04Options',
            A05: 'A05Options',
            A06: 'A06Options',
            A07: 'A07Options',
            A08: 'A08Options',
            A09: 'A09Options',

            B00: 'B00Options',
            B01: 'B01Options',
            B02: 'B02Options',
            B03: 'B03Options',
            B04: 'B04Options',
            B05: 'B05Options',
            B06: 'B06Options',
            B07: 'B07Options',
            B08: 'B08Options',
            B09: 'B09Options',
            B10: 'B10Options',
            B11: 'B11Options',
            B12: 'B12Options',
            B13: 'B13Options',
            B14: 'B14Options',
            B15: 'B15Options',
        }
        return (
            <div className='AddOptions'>
                <FormTempMapping
                    formItem={FlowThemeFormMapping[CLASSMAPPING[options]]}
                    FORMEVENT={FORMEVENT}
                    Initial={init}
                />
            </div>
        )
    }

    if (type === 'setBands') {
        const { field, bands } = init
        const [open, setOpen] = useState(false)
        const [TreeData, setTreeData] = useState()

        const onDrop = (info) => {
            const dropKey = info.node.id;
            const dragKey = info.dragNode.id;
            const dropPos = info.node.pos.split('-');
            const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
            const loop = (data, id, callback) => {
                for (let i = 0; i < data.length; i++) {
                    if (data[i].id === id) return callback(data[i], i, data)
                    if (data[i].children) loop(data[i].children, id, callback)
                }
            }
            const data = [...TreeData]
            let dragObj;
            loop(data, dragKey, (item, index, arr) => {
                arr.splice(index, 1)
                dragObj = item
            })
            if (!info.dropToGap) {
                loop(data, dropKey, item => {
                    item.children = item.children || []
                    item.children.unshift(dragObj);
                });
            } else {
                let ar = [], i
                loop(data, dropKey, (_item, index, arr) => { ar = arr; i = index })
                if (dropPosition === -1) ar.splice(i, 0, dragObj)
                else ar.splice(i + 1, 0, dragObj)
            }
            setTreeData(data);
        }

        useMount(() => {
            setTreeData(bands ? bands : field.filter(v => v.visible))
        })

        const onDel = (e) => {
            const { id, children } = e
            if (children.length !== 0) message.warning('请先清空分组下的字段')
            else setTreeData(removeTreeByKey(TreeData, id, 'id'))
        }

        const onSave = () => {
            FORMEVENT.emit({ type: 'onSaveBands', data: TreeData })
            Off()
        }

        const onClear = () => {
            FORMEVENT.emit({ type: 'onSaveBands', data: undefined })
            Off()
        }

        const BandsEvent = useEventEmitter()
        BandsEvent.useSubscription(val => {
            const { type, data } = val
            if (type === 'onFormBack') {
                setTreeData(e => ([{ ...data, id: v4(), visible: true }, ...e]))
                setOpen(false)
            }
        })

        if (TreeData) {
            return (
                <div className='SetAdminOptionsBands'>
                    <Tree
                        className='TreeBox'
                        blockNode
                        draggable
                        defaultExpandAll
                        treeData={TreeData}
                        fieldNames={{ key: 'id', title: 'caption' }}
                        selectedKeys={[]}
                        onDrop={onDrop}
                        titleRender={e => {
                            const status = e.dataField
                            return (
                                <div className='TreeItem'>
                                    <div>
                                        <div style={{ color: status ? '#003eb3' : '#36cfc9' }}>({status ? '接口数据' : '自增分组'})</div>
                                        <div>{e.caption}</div>
                                    </div>
                                    {!status &&
                                        <Popconfirm
                                            title="删除提醒!"
                                            description="是否要删除当前自增分组字段?"
                                            onConfirm={() => onDel(e)}
                                            okText="删除"
                                            cancelText="取消"
                                        >
                                            <Button type='link' danger>删除</Button>
                                        </Popconfirm>
                                    }
                                </div>
                            )
                        }}
                    />
                    <div>
                        <Popover
                            content={<FormTempMapping formItem={FlowThemeFormMapping['SetAdminOptionsBands']} FORMEVENT={BandsEvent} />}
                            destroyOnHidden
                            title="新增分组"
                            trigger="click"
                            open={open}
                            onOpenChange={setOpen}
                        >
                            <Button type='primary'>新增分组</Button>
                        </Popover>
                        <Button type='primary' onClick={onSave}>保存布局</Button>
                        <Button type='primary' danger onClick={onClear}>清空列头</Button>
                    </div>
                </div>
            )
        }
    }
};

export default SetAdminOptions;